package net.example.activity.adapter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nineoldandroids.view.ViewHelper;
import com.oraycn.esframework.core.FileEventListener;
import com.oraycn.omcs.MultimediaManagerFactory;
import com.oraycn.omcs.shortMessages.AudioMessage;
import com.oraycn.omcs.shortMessages.IAudioMessagePlayer;
import com.squareup.picasso.Picasso;

import net.example.activity.MainActivity;
import net.example.activity.UserDetailActivity;
import net.example.manager.ClientGlobalCache;
import net.example.model.GGUser;
import net.example.model.event.FileEvent;
import net.example.manager.Manager;
import net.example.activity.adapter.interfaces.IAdapterEventCallback;
import net.example.model.ChatInfo;
import net.example.ggtalk.R;
import net.example.utils.CircleCornerForm;
import net.example.utils.ConfigUtils;
import net.example.utils.HeadImgHelper;
import net.example.utils.LogHelper;
import net.example.activity.view.DropdownListView;
import net.example.activity.view.MyProgress;
import com.oraycn.esbasic.helpers.StringHelper;

import net.example.utils.android.IntentUtils;
import net.example.utils.io.BitmapUtil;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@SuppressLint("NewApi")
public class ChatLVAdapter extends BaseAdapter {
    /**
     * 执行动画的时间
     */
    protected long mAnimationTime = 150;
    private Context mContext;
    private int donw;
    private List<ChatInfo> list;
    /**
     * 弹出的更多选择框
     */
    private PopupWindow popupWindow;
    /**
     * 复制，删除
     */
    private View partition_line1;
    private TextView copy, delete,share;
    private LayoutInflater inflater;
    private DropdownListView mListView;
    private SimpleDateFormat dateFormat24 = new SimpleDateFormat("MM-dd HH:mm");
    private ChatInfo chatInfo;
    private ViewHolder holder;
    private IAdapterEventCallback iAdapterEventCallback;
    private AnimationDrawable audioPlayingDrawable;//当前正在播放语音动画的Drawable

    Logger log = Logger.getLogger(ChatLVAdapter.class);

    public ChatLVAdapter(Context mContext, List<ChatInfo> list, DropdownListView mlistv, IAdapterEventCallback iAdapterEventCallback) {
        super();
        this.mContext = mContext;
        this.list = list;
        this.mListView = mlistv;
        this.iAdapterEventCallback=iAdapterEventCallback;
        inflater = LayoutInflater.from(mContext);
        initPopWindow();
    }

    public void fileCancel(String projectID) {
        int position = -1;
        for (int x = list.size() - 1; x >= 0; x--) {
            ChatInfo msg = list.get(x);
            if (msg.getFileMessage() != null && projectID.equals(msg.getFileMessage().projectId)) {
                //msg.file.transferSize=transferSize;
                position = x;
                break;
            }
        }
        int fpos = mListView.getFirstVisiblePosition();
        View v = mListView.getChildAt(position - fpos + 1);
        if (v != null) {
            ViewHolder holder = (ViewHolder) v.getTag();
            holder.ct_status_from.setVisibility(View.VISIBLE);
            holder.pb_sending_left.setVisibility(View.GONE);
            holder.ct_status_from.setImageResource(R.drawable.failed);
        }
    }

    public void fileDisrupptted(FileEvent event) {
        int position = -1;
        ChatInfo msg = null;
        for (int x = list.size() - 1; x >= 0; x--) {
            msg = list.get(x);
            if (msg.getFileMessage() != null && event.ProjectId.equals(msg.getFileMessage().projectId)) {
                //msg.file.transferSize=transferSize;
                position = x;
                break;
            }
        }
        int fpos = mListView.getFirstVisiblePosition();
        View v = mListView.getChildAt(position - fpos + 1);
        if (v != null) {
            ViewHolder holder = (ViewHolder) v.getTag();

            if (event.DisrupttedType == FileEventListener.FileTransDisrupttedType.AnswerFileRequestOnOtherDevice) {
                holder.ct_status_from.setVisibility(View.VISIBLE);
                holder.pb_sending_left.setVisibility(View.GONE);
                holder.ct_status_from.setImageResource(R.drawable.failed);
                holder.tv_file_state_left_text.setText(msg.getFileStateMsg());
            } else {
                holder.ct_status_to.setVisibility(View.VISIBLE);
                holder.pb_sending.setVisibility(View.GONE);
                holder.ct_status_to.setImageResource(R.drawable.failed);
            }
        }
    }

    public void fileResp(FileEvent event) {
        int position = -1;
        ChatInfo msg = null;
        for (int x = list.size() - 1; x >= 0; x--) {
            msg = list.get(x);
            if (msg.getFileMessage() != null && event.ProjectId.equals(msg.getFileMessage().projectId)) {
                //msg.file.transferSize=transferSize;
                position = x;
                break;
            }
        }
        int fpos = mListView.getFirstVisiblePosition();
        View v = mListView.getChildAt(position - fpos + 1);
        if (v != null) {
            list.get(position).setAcceptFile(event.Accpet);
            String txt = event.Accpet ? "同意接收文件" : "拒绝接收文件";
            if(event.Accpet) {
                msg.setFileStateMsg(txt);
            }

            ViewHolder holder = (ViewHolder) v.getTag();
            if (holder != null && msg.getFromOrTo() == 0) {//Received
                holder.ct_status_to.setVisibility(View.VISIBLE);
                holder.pb_sending.setVisibility(View.GONE);
                holder.ct_status_to.setImageResource(R.drawable.failed);
                holder.tv_file_state_to_text.setText(msg.getFileStateMsg());

            } else if (holder != null && msg.getFromOrTo() == 1) {
                if (event.Accpet) {
                    holder.ct_status_to.setVisibility(View.GONE);
                    holder.pb_sending.setVisibility(View.VISIBLE);
                    holder.tv_file_state_to_text.setText(msg.getFileStateMsg());
                }else{
                    holder.pb_sending.setVisibility(View.GONE);
                    holder.ct_status_to.setVisibility(View.VISIBLE);
                    holder.ct_status_to.setImageResource(R.drawable.failed);
                    holder.tv_file_state_to_text.setVisibility(View.VISIBLE);
                    holder.tv_file_state_to_text.setText(msg.getFileStateMsg());
                }
            }
        }
    }

    public void updateProcess(FileEvent event) {
        switch (event.Type) {
            case FileEvent.FILE_PROCESS:
                fileProcess(event);
                break;
            case FileEvent.FILE_RESP:
                fileResp(event);
                break;
            case FileEvent.CANCEL_TRANSFERING:
                fileCancel(event.ProjectId);
                break;
            case FileEvent.FILE_TRANS_DISRUPPTTED:
                fileDisrupptted(event);
                break;
            case FileEvent.FILE_COMPLETED:
                fileCompleted(event);
                break;
        }
    }

    private void fileProcess(FileEvent event) {
        String projectID = event.ProjectId;
        int total =  (int)event.FileSize;
        int transferSize = event.TransferSize;
        int position = -1;
        for (int x = list.size() - 1; x >= 0; x--) {
            ChatInfo msg = list.get(x);
            if (msg.getFileMessage() != null && projectID.equals(msg.getFileMessage().projectId)) {
                //msg.file.transferSize=transferSize;
                position = x;
                break;
            }
        }
        int fpos = mListView.getFirstVisiblePosition();
        View v = mListView.getChildAt(position - fpos + 1);
        if (v != null) {

            ChatInfo msg = list.get(position);
            ViewHolder holder = (ViewHolder) v.getTag();
            if (holder != null && msg.getFromOrTo() == 0) {//Received
                holder.pb_sending_left.setVisibility(View.VISIBLE);
                holder.pb_sending_left.setMax(total);
                holder.pb_sending_left.setProgress(transferSize);
                if (total == transferSize) {
                    holder.ct_status_from.setVisibility(View.VISIBLE);
                    holder.ct_status_from.setImageResource(R.drawable.complete);
                    holder.pb_sending_left.setVisibility(View.GONE);
                    msg.setFileHasDown(true);
                }

            } else if (holder != null && msg.getFromOrTo() == 1) {//send
                holder.pb_sending.setVisibility(View.VISIBLE);
                holder.pb_sending.setMax(total);
                holder.pb_sending.setProgress(transferSize);
                if (total == transferSize) {
                    holder.pb_sending.setVisibility(View.GONE);
                    holder.ct_status_to.setVisibility(View.VISIBLE);
                    holder.ct_status_to.setImageResource(R.drawable.complete);
                    msg.setFileHasDown(true);
                }
            }
        }
    }

    private void fileCompleted(FileEvent event) {
        String projectID = event.ProjectId;
        int position = -1;
        for (int x = list.size() - 1; x >= 0; x--) {
            ChatInfo msg = list.get(x);
            if (msg.getFileMessage() != null && projectID.equals(msg.getFileMessage().projectId)) {
                //msg.file.transferSize=transferSize;
                position = x;
                break;
            }
        }
        int fpos = mListView.getFirstVisiblePosition();
        View v = mListView.getChildAt(position - fpos + 1);
        if (v != null) {

            ChatInfo msg = list.get(position);
            ViewHolder holder = (ViewHolder) v.getTag();
            if (holder != null && msg.getFromOrTo() == 0) {//Received

                holder.ct_status_from.setVisibility(View.VISIBLE);
                holder.ct_status_from.setImageResource(R.drawable.complete);
                holder.pb_sending_left.setVisibility(View.GONE);
                msg.setFileHasDown(true);

            } else if (holder != null && msg.getFromOrTo() == 1) {//send
                holder.pb_sending.setVisibility(View.GONE);
                holder.ct_status_to.setVisibility(View.VISIBLE);
                holder.ct_status_to.setImageResource(R.drawable.complete);
                msg.setFileHasDown(true);
            }
        }
    }

    public void setList(List<ChatInfo> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public int getItemViewType(int position) {
        chatInfo = (ChatInfo) getItem(position);
        if (chatInfo.getImageUrl() != null && !chatInfo.getImageUrl().equals("")) {
            return ChatInfo.chat_img_item;
        } else if (chatInfo.getFileMessage() != null && !chatInfo.getFileMessage().fileName.equals("")) {
            return ChatInfo.chat_file_item;
        } else if (chatInfo.getAudioMessage() != null) {
            return ChatInfo.chat_audio_item;
        } else {
            return ChatInfo.chat_lv_item;
        }
    }


    @Override
    public int getViewTypeCount() {
        return 4;
    }

    public void updateItem(int position, ListView parent)
    {
        try {
            if(position<0)
            {
                return;
            }
            /**第一个可见的位置  -1是减去第一个View HeaderView的位置 **/
            int firstVisiblePosition = parent.getFirstVisiblePosition()-1;
            /**最后一个可见的位置**/
            int lastVisiblePosition = parent.getLastVisiblePosition()-1;
            /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
            if ((position >= firstVisiblePosition && position <= lastVisiblePosition)) {
                /**获取指定位置view对象**/
                View view = parent.getChildAt(position - firstVisiblePosition);
                getView(position, view, parent);
            }
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try {
            int type = getItemViewType(position);
            convertView=this.getConvertView(position,type,convertView);
            holder = (ViewHolder) convertView.getTag();
            setViewSendTime(position);
            // 收到消息 from显示
            if (list.get(position).getFromOrTo() == 0) {
                showView(position,convertView, type);
            } else {//发送消息
                setViewSend(position, convertView, type);
            }
            return convertView;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    private View getConvertView(int position, int type ,View convertView)
    {
        if (convertView == null) {
            if (type == ChatInfo.chat_img_item) {
                convertView = getImgView(position);
            } else if (type == ChatInfo.chat_file_item) {
                donw = 0;
                convertView = getFileView(position);
            } else if (type == ChatInfo.chat_audio_item) {
                convertView = getAudioView(position);
            } else if (type == ChatInfo.chat_lv_item) {
                convertView = getTextView();
            }
        }
        ViewHolder holder = (ViewHolder) convertView.getTag();
        if (holder != null) {
            holder.chatInfo = list.get(position);
            holder.fromIcon.setOnClickListener(new HeadIconClickListener(list.get(position)));
            holder.toIcon.setOnClickListener(new HeadIconClickListener(list.get(position)));
        }
        return convertView;
    }

    private void showView(int position,View convertView, int type) {
        try
        {
            holder.toContainer.setVisibility(View.GONE);
            holder.fromContainer.setVisibility(View.VISIBLE);
            GGUser GGUser =ClientGlobalCache.getInstance().getUser(list.get(position).getHeadFromUserID());
            HeadImgHelper.setUserHeadImg(holder.fromIcon, GGUser);
            if (type == ChatInfo.chat_img_item) {
                showImgView(position,convertView);
            } else if (type == ChatInfo.chat_file_item) {
                showFileView(position);
            } else if (type == ChatInfo.chat_audio_item) {
                showAudioView(position);
            } else {
                showTextView(position ,convertView);
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }

    private void setViewSend(int position, View convertView, int type) {
        try
        {
            holder.toContainer.setVisibility(View.VISIBLE);
            holder.fromContainer.setVisibility(View.GONE);
            HeadImgHelper.setUserHeadImg(holder.toIcon, ClientGlobalCache.getInstance().getCurrentUser());

            if (type == ChatInfo.chat_img_item) {
                setImgViewSend(position,convertView);
            } else if (type == ChatInfo.chat_file_item) {
                setFileViewSend();
            } else if (type == ChatInfo.chat_audio_item) {
                setAudioViewSend(position);
            } else {
                setTextViewSend(position, convertView);
            }

        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }


    private void setViewSendTime(int position) {
        Date lastRecordTime=new Date(0);
        Date positionDate = list.get(position).getTime();
        if(position-1>=0)
        {
            lastRecordTime=list.get(position-1).getTime();
        }
        long diff = positionDate.getTime() - lastRecordTime.getTime();

        if (Math.abs(diff) < 5 * 60 * 1000) {
            holder.time.setVisibility(View.GONE);
        } else {
            holder.time.setText(dateFormat24.format(positionDate));
            holder.time.setVisibility(View.VISIBLE);
        }

    }

    private void setTextViewSend(int position, View convertView) {
        // 对内容做处理
          SpannableStringBuilder sb = handler(holder.toContent,
                list.get(position).getContent());
          Log.i("position:","pos:"+position+ "count:"+list.size());
        holder.toContent.setText(sb);
        // 设置+按钮点击效果
        holder.fromContent.setOnLongClickListener(new popAction(
                convertView, position, list.get(position).getFromOrTo()));
        holder.toContent.setOnLongClickListener(new popAction(
                convertView, position, list.get(position).getFromOrTo()));
        if(StringHelper.isNullOrEmpty(holder.chatInfo.snapchatMessageID))//通过激活设置背景图
        {
            holder.toContent.setActivated(false);
        }
        else {
            holder.toContent.setActivated(true);
        }
    }

    private void setAudioViewSend(int position) {
        // 对内容做处理
        int seconds=Math.round((list.get(position).getAudioMessage().spanInMSecs + 1000) / 1000);
        holder.toContent.setText(seconds + "‘");
       // holder.fromContent.setText(Math.round((list.get(position).getAudioMessage().spanInMSecs + 1000) / 1000) + "‘");
//        if (!chatInfo.getAudioMessage().isAnimation()) {
//         //   ((AnimationDrawable) holder.fromImgContent.getDrawable()).setOneShot(false);
//            AnimationDrawable drawable= ((AnimationDrawable) holder.toImgContent.getDrawable());
//            Thread thread= new Thread(new AudioPlayAnimation(drawable,seconds));
//            thread.start();
//        }
    }
    private class AudioPlayAnimation implements Runnable
    {
        private AnimationDrawable animationDrawable;
        private int seconds=0;
        public AudioPlayAnimation(AnimationDrawable drawable,int seconds)
        {
            this.animationDrawable=drawable;
            this.seconds=seconds;
        }
        @Override
        public void run() {
            try {
                Thread.sleep((this.seconds-1)*1000);
                if(this.animationDrawable!=null)
                {
                    this.animationDrawable.setOneShot(true);//动画执行N秒后停止
                }
                Thread.sleep(1000);
                clearAudioPlayingDrawable();
                MultimediaManagerFactory.GetSingleton().getAudioMessagePlayer().stop();
//                this.animationDrawable.start();
            }catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    private int audioMessageID =-1;//当前正在播放的语音消息ID
    private void clearAudioPlayingDrawable()
    {
        audioPlayingDrawable = null;
        audioMessageID =-1;
    }

    private void setFileViewSend() {

        holder.file_lin.setVisibility(View.VISIBLE);
        holder.pb_sending.setVisibility(View.VISIBLE);
        holder.file_size.setText((chatInfo.getFileMessage().fileSize / 1024) + "k");
        if (chatInfo.isFileHasDown()) {
            holder.tv_file_state_to_text.setVisibility(View.GONE);
            holder.pb_sending.setMax(chatInfo.getFileMessage().fileSize);
            holder.pb_sending.setProgress(chatInfo.getFileMessage().fileSize);
            holder.ct_status_to.setVisibility(View.VISIBLE);
            holder.ct_status_to.setImageResource(R.drawable.complete);
        }else if(!chatInfo.getAcceptFile()){
            holder.pb_sending.setVisibility(View.GONE);
            holder.ct_status_to.setVisibility(View.VISIBLE);
            holder.ct_status_to.setImageResource(R.drawable.failed);
            if(chatInfo.getFileStateMsg()!=null){
            }
        }
        if(chatInfo.getFileStateMsg()!=null){
            holder.tv_file_state_to_text.setText(chatInfo.getFileStateMsg());
        }
        holder.file_name.setText(chatInfo.getFileMessage().fileName);
        LogHelper.e(chatInfo.getFileMessage().fileName);
    }

    private void setImgViewSend(int position, View convertView) {
        try {
            Uri uri=Uri.fromFile(new File(list.get(position).getImageUrl()));
            Size size=BitmapUtil.getImgSize(uri.getPath());
            Size newSize= BitmapUtil.getZoomSize(size.getWidth(),size.getHeight(),600);
            Picasso.get().load(uri).error(R.drawable.default_image).transform(new CircleCornerForm()).resize(newSize.getWidth(),newSize.getHeight()).into(holder.toImgContent);
            holder.toImgContent.setOnLongClickListener(new popAction(convertView,position,list.get(position).getFromOrTo()));
            HeadImgHelper.setUserHeadImg(holder.toIcon, ClientGlobalCache.getInstance().getCurrentUser());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void showTextView(final int position , View convertView) {
        SpannableStringBuilder sb = handler(holder.fromContent,
                list.get(position).getContent());
        //若是系统消息 不显示下方头像及气泡内容
        if(StringHelper.isNullOrEmpty(chatInfo.getSpeakerID()))
        {
           holder.container_item.setVisibility(View.GONE);
           holder.tv_system_msg.setText(sb);
           holder.tv_system_msg.setVisibility(View.VISIBLE);
           return;
        }
        else {
            holder.container_item.setVisibility(View.VISIBLE);
            holder.tv_system_msg.setVisibility(View.GONE);
        }
        if (chatInfo.isGroupChat()) {
            holder.chatTitle.setText(chatInfo.getSourceName());
            holder.chatTitle.setVisibility(View.VISIBLE);
        }
        else {
            holder.chatTitle.setVisibility(View.GONE);
        }
        holder.tv_countdown_label.setVisibility(View.GONE);
        if(StringHelper.isNullOrEmpty(holder.chatInfo.snapchatMessageID))
        {
            holder.fromContent.setText(sb);
            holder.fromContent.setOnLongClickListener(new popAction(
                    convertView, position, list.get(position).getFromOrTo()));
            holder.toContent.setOnLongClickListener(new popAction(
                    convertView, position, list.get(position).getFromOrTo()));
        }
        else if(!holder.chatInfo.isRead()){
            SpannableStringBuilder spannableString = new SpannableStringBuilder();
            spannableString.append("点击查看[悄悄话]");
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.red));
            spannableString.setSpan(colorSpan,4,9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.fromContent.setText(spannableString);

            holder.fromContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(iAdapterEventCallback!=null)
                    {
                        iAdapterEventCallback.onSnapchatMessageClicked(position);
                    }
                }
            });
        }
        else {
            holder.tv_countdown_label.setVisibility(View.VISIBLE);
            holder.tv_countdown_label.setText(String.valueOf(holder.chatInfo.snapchatMessageShowSeconds));
            holder.fromContent.setText(sb);
        }

    }
//    private ViewHolder tempHolder;

    private void showAudioView(int position) {
        if (chatInfo.isGroupChat()) {
            holder.chatTitle.setText(chatInfo.getSourceName());
        }
        int seconds=Math.round((list.get(position).getAudioMessage().spanInMSecs + 1000) / 1000);
        holder.fromContent.setText(seconds + "‘");
      //  holder.toContent.setText(Math.round((list.get(position).getAudioMessage().spanInMSecs + 1000) / 1000) + "‘");
//        if (!chatInfo.getAudioMessage().isAnimation()) {
//            AnimationDrawable drawable=  ((AnimationDrawable) holder.fromImgContent.getDrawable());
//            Thread thread = new Thread(new AudioPlayAnimation(drawable,seconds));
//            thread.start();
       //     ((AnimationDrawable) holder.toImgContent.getDrawable()).setOneShot(false);
//        }
    }

    private void showFileView(int position) {
        holder.fromImgContent
                .setImageResource(R.drawable.chat_item_file);
        holder.file_name_left.setText(list.get(position).getFileMessage().fileName);
        holder.file_size_left.setText((list.get(position).getFileMessage().fileSize / 1024) + "k");
        if (chatInfo.isFileHasDown()) {
            holder.ct_status_from.setVisibility(View.VISIBLE);
            holder.ct_status_from.setImageResource(R.drawable.complete);
            holder.tv_file_state_left_text.setVisibility(View.GONE);
        } else if (!chatInfo.getAcceptFile()) {
            holder.ct_status_from.setVisibility(View.VISIBLE);
            holder.ct_status_from.setImageResource(R.drawable.failed);
            if(chatInfo.getFileStateMsg()!=null) {
                holder.tv_file_state_left_text.setText(chatInfo.getFileStateMsg());
            }
        }
    }
    private void showImgView(int position,View convertView) {
        try{
            Uri uri =Uri.fromFile(new File(list.get(position).getImageUrl()));
            Size size=BitmapUtil.getImgSize(uri.getPath());
            Size newSize= BitmapUtil.getZoomSize(size.getWidth(),size.getHeight(),600);
           // holder.fromImgContent.setImageURI(uri);

        Picasso.get().load(uri).error(R.drawable.default_image).transform(new CircleCornerForm()).resize(newSize.getWidth(),newSize.getHeight()).into(holder.fromImgContent);
        holder.fromImgContent.setOnLongClickListener(new popAction(convertView,position,list.get(position).getFromOrTo()));
        }catch (Exception ex){
            ex.printStackTrace();
        }
        if (chatInfo.isGroupChat()) {
            holder.chatTitle.setText(chatInfo.getSourceName());
        }

    }
    @NonNull
    private View getImgView(final int position) {
        View convertView;
        convertView = LayoutInflater.from(mContext).inflate(
                R.layout.chat_img_item, null);
        holder = new ViewHolder();
        holder.fromContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_from_container);
        holder.toContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_to_container);
        holder.fromImgContent = (ImageView) convertView
                .findViewById(R.id.chatfrom_img_content);
        holder.toImgContent = (ImageView) convertView
                .findViewById(R.id.chatto_img_content);
        holder.time = (TextView) convertView
                .findViewById(R.id.chat_time);
        holder.fromIcon = (ImageView) convertView.findViewById(R.id.chatfrom_icon);
        holder.toIcon = (ImageView) convertView.findViewById(R.id.chatto_icon);
        holder.chatTitle = (TextView) convertView.findViewById(R.id.chatTitle);
        holder.position = position;
        holder.fromImgContent.setOnClickListener(new ImageClickListener(convertView));
        holder.toImgContent.setOnClickListener(new ImageClickListener(convertView));
        convertView.setTag(holder);
        return convertView;
    }
    @NonNull
    private View getFileView(final int position) {
        View convertView;
        holder = new ViewHolder();
        convertView = LayoutInflater.from(mContext).inflate(
                R.layout.chat_file_item, null);
        holder.pb_sending = (MyProgress) convertView
                .findViewById(R.id.progressBar);
        holder.pb_sending_left = (MyProgress) convertView
                .findViewById(R.id.progressBar_left);
        holder.fromContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_from_container);
        holder.toContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_to_container);
        holder.tv_file_state_left_text = (TextView) convertView
                .findViewById(R.id.tv_file_state_left_text);
        holder.fromContent = (TextView) convertView
                .findViewById(R.id.chatfrom_content);
        holder.tv_countdown_label=(TextView)convertView.findViewById(R.id.countdown_label);
        holder.toContent = (TextView) convertView
                .findViewById(R.id.chatto_content);
        holder.time = (TextView) convertView
                .findViewById(R.id.chat_time);
        holder.fromImgContent = (ImageView) convertView
                .findViewById(R.id.chatfrom_img_content);
        holder.toImgContent = (ImageView) convertView
                .findViewById(R.id.chatto_img_content);
        holder.ct_status_from = (ImageView) convertView
                .findViewById(R.id.ct_status_from);
        holder.ct_status_to = (ImageView) convertView
                .findViewById(R.id.ct_status_to);
        holder.file_name = (TextView) convertView
                .findViewById(R.id.file_name);
        holder.file_name_left = (TextView) convertView
                .findViewById(R.id.file_name_left);
        holder.file_size_left = (TextView) convertView
                .findViewById(R.id.file_size_left);
        holder.file_size = (TextView) convertView
                .findViewById(R.id.file_size);
        holder.file_lin_left = (ViewGroup) convertView
                .findViewById(R.id.file_lin_left);
        holder.file_lin = (ViewGroup) convertView
                .findViewById(R.id.file_lin);
        holder.tv_file_state_to_text = (TextView) convertView
                .findViewById(R.id.tv_file_state_to_text);
        holder.fromIcon = (ImageView) convertView.findViewById(R.id.chatfrom_icon);
        holder.toIcon = (ImageView) convertView.findViewById(R.id.chatto_icon);
        holder. position = position;
        convertView.setTag(holder);
        holder.tv_file_state_left_text.setVisibility(View.VISIBLE);
        holder.fromContainer.setOnClickListener( new FileClickListener(convertView) );
        holder.toContainer.setOnClickListener(new FileClickListener(convertView));
        return convertView;
    }

    private View getTextView() {
        View convertView;
        convertView = LayoutInflater.from(mContext).inflate(
                R.layout.chat_lv_item, null);
        holder = new ViewHolder();
        holder.container_item=(ViewGroup)convertView.findViewById(R.id.container_item) ;
        holder.fromContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_from_container);
        holder.toContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_to_container);
        holder.fromContent = (TextView) convertView
                .findViewById(R.id.chatfrom_content);
        holder.tv_countdown_label=(TextView)convertView.findViewById(R.id.countdown_label);
        holder.toContent = (TextView) convertView
                .findViewById(R.id.chatto_content);
        holder.time = (TextView) convertView
                .findViewById(R.id.chat_time);
        holder.tv_system_msg=(TextView)convertView.findViewById(R.id.system_msg);
        holder.fromIcon = (ImageView) convertView.findViewById(R.id.chatfrom_icon);
        holder.toIcon = (ImageView) convertView.findViewById(R.id.chatto_icon);
        holder.chatTitle = (TextView) convertView.findViewById(R.id.chatTitle);
        convertView.setTag(holder);
        return convertView;
    }

    private View getAudioView(int position) {
        View convertView = LayoutInflater.from(mContext).inflate(
                R.layout.chat_audio_item, null);
        holder = new ViewHolder();
        holder.fromContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_from_container);
        holder.toContainer = (ViewGroup) convertView
                .findViewById(R.id.chart_to_container);
        holder.fromContent = (TextView) convertView
                .findViewById(R.id.chatTitle);
        holder.tv_countdown_label=(TextView)convertView.findViewById(R.id.countdown_label);
        holder.toContent = (TextView) convertView
                .findViewById(R.id.chatto_content_span);
        holder.fromImgContent = (ImageView) convertView
                .findViewById(R.id.chatfrom_img_content);
        holder.toImgContent = (ImageView) convertView
                .findViewById(R.id.chatto_img_content);
        chatInfo.getAudioMessage().setAnimation(false);
        holder.time = (TextView) convertView
                .findViewById(R.id.chat_time);
        holder.fromIcon = (ImageView) convertView.findViewById(R.id.chatfrom_icon);
        holder.toIcon = (ImageView) convertView.findViewById(R.id.chatto_icon);
        holder.position = position;
        convertView.setTag(holder);
        holder.fromImgContent.setOnClickListener(new AudioClickListener(convertView,position));
        holder.toImgContent.setOnClickListener(new AudioClickListener(convertView,position));
        return convertView;
    }

    private SpannableStringBuilder handler(final TextView gifTextView,
                                           String content) {

        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String png = tempText.substring("#[".length(),
                        tempText.length() - "]#".length());

                try {
                    Bitmap image=BitmapFactory.decodeStream(mContext.getAssets().open(png));
                    image.setDensity(200);
                    sb.setSpan(
                            new ImageSpan(mContext, image), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
//                String num = tempText.substring(
//                        "#[face/png/f_static_".length(), tempText.length()
//                                - ".png]#".length());
//                String gif = "face/gif/f" + num + ".gif";
//                /**
//                 * 如果open这里不抛异常说明存在gif，则显示对应的gif 否则说明gif找不到，则显示png
//                 * */
//                Bitmap image=BitmapFactory.decodeStream(mContext.getAssets().open(gif));
//                image.setDensity(200);
//                Drawable drawable=ImageHelper.bitmapToDrawable(image,mContext);
//                InputStream is =  mContext.getAssets().open(gif);//new ByteArrayInputStream(ImageHelper.bitmapToByteArray(image,false));
//                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is,
//                                new AnimatedGifDrawable.UpdateListener() {
//
//                                    @Override
//                                    public void update() {
//                                        gifTextView.postInvalidate();
//                                    }
//                                })), m.start(), m.end(),
//                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//               is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(),
                        tempText.length() - "]#".length());

                try {
                    Bitmap image=BitmapFactory.decodeStream(mContext.getAssets().open(png));
                    image.setDensity(200);
                    sb.setSpan(
                            new ImageSpan(mContext, image), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
        }
        return sb;
    }

    /**
     * 屏蔽listitem的所有事件
     */
    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        return false;
    }

    /**
     * 初始化弹出的pop
     */
    private void initPopWindow() {
        View popView = inflater.inflate(R.layout.chat_item_copy_delete_menu, null);
        copy = (TextView) popView.findViewById(R.id.chat_copy_menu);
        share=(TextView)popView.findViewById(R.id.chat_share_menu);
        delete = (TextView) popView.findViewById(R.id.chat_delete_menu);
        partition_line1=(View)popView.findViewById(R.id.partition_line1);
        popupWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
    }

    /**
     * 显示popWindow
     */
    public void showPop(View parent, int x, int y, final View view,
                        final int position, final int fromOrTo) {
        // 设置popwindow显示位置
        popupWindow.showAtLocation(parent, 0, x, y);
        // 获取popwindow焦点
        popupWindow.setFocusable(true);
        // 设置popwindow如果点击外面区域，便关闭。
        popupWindow.setOutsideTouchable(true);

        ChatInfo chatInfo= list.get(position);
        if(!StringHelper.isNullOrEmpty(chatInfo.getImageUrl()) )
        {
            copy.setVisibility(View.GONE);
            partition_line1.setVisibility(View.GONE);
        }
        else {
            copy.setVisibility(View.VISIBLE);
            partition_line1.setVisibility(View.VISIBLE);
        }
        // 为按钮绑定事件
        // 复制
        copy.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                // 获取剪贴板管理服务
                ClipboardManager cm = (ClipboardManager) mContext
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本数据复制到剪贴板
                cm.setText(list.get(position).getContent());
            }
        });
        //隐藏转发
       // share.setVisibility(View.GONE);
       // partition_line1.setVisibility(View.GONE);
        //转发
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                if (iAdapterEventCallback != null) {
                    ChatInfo chatInfo =list.get(position);
                    iAdapterEventCallback.onShareMessage(chatInfo);
                }
            }
        });
        // 删除
        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                if (fromOrTo == 0) {
                    leftRemoveAnimation(view, position);
                } else if (fromOrTo == 1) {
                    rightRemoveAnimation(view, position);
                }
            }
        });
        popupWindow.update();
    }

    /**
     * item删除动画
     */
    private void rightRemoveAnimation(final View view, final int position) {
        final Animation animation = (Animation) AnimationUtils.loadAnimation(
                mContext, R.anim.chatto_remove_anim);
        animation.setAnimationListener(new AnimationListener() {
            public void onAnimationStart(Animation animation) {
            }

            public void onAnimationRepeat(Animation animation) {
            }

            public void onAnimationEnd(Animation animation) {
                view.setAlpha(0);
                performDismiss(view, position);
                animation.cancel();
            }
        });

        view.startAnimation(animation);
    }

    /**
     * item删除动画
     */
    private void leftRemoveAnimation(final View view, final int position) {
        final Animation animation = (Animation) AnimationUtils.loadAnimation(
                mContext, R.anim.chatfrom_remove_anim);

        animation.setAnimationListener(new AnimationListener() {
            public void onAnimationStart(Animation animation) {
            }

            public void onAnimationRepeat(Animation animation) {
            }

            public void onAnimationEnd(Animation animation) {
                view.setAlpha(0);
                performDismiss(view, position);
                animation.cancel();
            }
        });

        view.startAnimation(animation);
    }

    /**
     * 在此方法中执行item删除之后，其他的item向上或者向下滚动的动画，并且将position回调到方法onDismiss()中
     *
     * @param dismissView
     * @param dismissPosition
     */
    private void performDismiss(final View dismissView,
                                final int dismissPosition) {
        final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();// 获取item的布局参数
        final int originalHeight = dismissView.getHeight();// item的高度

        ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 0)
                .setDuration(mAnimationTime);
        animator.start();

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                list.remove(dismissPosition);
                notifyDataSetChanged();
                // 这段代码很重要，因为我们并没有将item从ListView中移除，而是将item的高度设置为0
                // 所以我们在动画执行完毕之后将item设置回来
                ViewHelper.setAlpha(dismissView, 1f);
                ViewHelper.setTranslationX(dismissView, 0);
                ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
                lp.height = originalHeight;
                dismissView.setLayoutParams(lp);
            }
        });

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                // 这段代码的效果是ListView删除某item之后，其他的item向上滑动的效果
                lp.height = (Integer) valueAnimator.getAnimatedValue();
                dismissView.setLayoutParams(lp);
            }
        });

    }
    @Override
    public void notifyDataSetChanged()
    {
//        convertViews.clear();
        super.notifyDataSetChanged();
    }

    class ViewHolder {
        ImageView fromIcon, toIcon, fromImgContent, toImgContent, ct_status_to, ct_status_from;
        TextView fromContent, toContent, time, file_name, file_name_left, file_size_left, file_size, chatTitle, tv_file_state_left_text, tv_file_state_to_text, tv_system_msg, tv_countdown_label;
        ViewGroup container_item, fromContainer, toContainer, file_lin_left, file_lin;
        MyProgress pb_sending, pb_sending_left;
        int position;
        ChatInfo chatInfo;
    }

    /**
     * 每个ITEM中more按钮对应的点击动作
     */
    public class popAction implements OnLongClickListener {
        int position;
        View view;
        int fromOrTo;

        public popAction(View view, int position, int fromOrTo) {
            this.position = position;
            this.view = view;
            this.fromOrTo = fromOrTo;
        }

        @Override
        public boolean onLongClick(View v) {

            int[] arrayOfInt = new int[2];
            // 获取点击按钮的坐标
            v.getLocationOnScreen(arrayOfInt);
            int x = arrayOfInt[0];
            int y = arrayOfInt[1];
            showPop(v, x, y, view, position, fromOrTo);
            return true;
        }
    }

    private class ImageClickListener implements View.OnClickListener {
        private View convertView;
        public ImageClickListener(View convertView) {
            this.convertView = convertView;
        }
        @Override
        public void onClick(View v) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            ChatInfo info = holder.chatInfo;
            if (iAdapterEventCallback != null) {
                iAdapterEventCallback.onImageClicked(info);
            }
        }
    }
    private Thread audioPlayingThread =null;
    private class AudioClickListener implements View.OnClickListener {
        private View convertView;
        private int position;

        public AudioClickListener(View convertView, int position) {
            this.convertView = convertView;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            try {
                ImageView view = ((ImageView) v);
                //释放原来的播放内容，重新播放当前内容
                ViewHolder holder = (ViewHolder) convertView.getTag();
                ChatInfo info = holder.chatInfo;
                holder.toImgContent.setImageResource(R.drawable.voice_to_icon);
                holder.fromImgContent.setImageResource(R.drawable.voice_from_icon);
                if (iAdapterEventCallback != null) {
                    iAdapterEventCallback.onAudioClicked(this.position, info.getAudioMessage());
                }
                Log.i("ChatLVAdapter", "onClick:" + info.getAudioMessage());
//                IAudioMessagePlayer audioPlayer=MultimediaManagerFactory.GetSingleton().getAudioMessageController().getAudioMessagePlayer();
//                audioPlayer.stop();
                if (audioPlayingThread != null) {
                    audioPlayingThread.interrupt();
                }
                if (audioPlayingDrawable != null) {
                    audioPlayingDrawable.stop();
                    audioPlayingDrawable.selectDrawable(0);
                    if (audioMessageID == info.getAudioMessage().iD)//当前正在播放的语音消息，再次被点击后，停止播放
                    {
                        clearAudioPlayingDrawable();
                        return;
                    }
                }
                audioMessageID = info.getAudioMessage().iD;
                AnimationDrawable animationDrawable = ((AnimationDrawable) view.getDrawable());
                int seconds = Math.round((list.get(position).getAudioMessage().spanInMSecs + 1000) / 1000);
                animationDrawable.setOneShot(false);
                animationDrawable.start();
                audioPlayingThread = new Thread(new AudioPlayAnimation(animationDrawable, seconds));
                audioPlayingThread.start();
                audioPlayingDrawable = animationDrawable;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private class FileClickListener implements View.OnClickListener {
        private View convertView;
        private boolean down;

        public FileClickListener(View convertView) {
            this.convertView = convertView;
        }

        @Override
        public void onClick(View v) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            ChatInfo info = holder.chatInfo;
            if (!info.isFileHasDown()) {
                if (info.getAcceptFile()) {
                    if (!down) {
                        holder.pb_sending_left.setVisibility(View.VISIBLE);
                        holder.tv_file_state_left_text.setVisibility(View.GONE);
                        holder.file_lin_left.setVisibility(View.GONE);
                        down = true;
                        Manager.getInstance().acceptFile(info.getFileMessage().projectId, ConfigUtils.SDFileSavePath + info.getFileMessage().fileName);

                    } else {
                        down = false;
                        Manager.getInstance().cancelTransfering(info.getFileMessage().projectId);
                        info.setAcceptFile(false);
                        holder.pb_sending_left.setVisibility(View.GONE);
                    }
                }
            }
            else {
                if (iAdapterEventCallback != null) {
                    iAdapterEventCallback.onFileClicked(info);
                }
            }
        }
    }

    private class HeadIconClickListener implements View.OnClickListener
    {
        private ChatInfo chatInfo;
        public HeadIconClickListener(ChatInfo chatInfo)
        {
            this.chatInfo=chatInfo;
        }
        @Override
        public void onClick(View v) {
            if(chatInfo.getFromOrTo()==0)//收到消息
            {
                IntentUtils.startActivityForString(mContext, UserDetailActivity.class,"requestID",chatInfo.getHeadFromUserID());
            }else if(chatInfo.getFromOrTo()==1)//发送消息
            {
                Intent intent = new Intent(mContext, MainActivity.class);
                intent.putExtra("tabID", R.id.btn_main_setting);
                mContext.startActivity(intent);
            }
        }
    }


}
